﻿using System.Text.RegularExpressions;

namespace CEFdemo
{
    public class ConvertHTML
    {
        public static string convertToHtml(string markdownString)
        {
            string htmlString = "<p>";
            string[] markdownStrings = GetLines(markdownString);
            for (int i = 0; i < markdownStrings.Length; i++)
            {
                string mdString = markdownStrings[i];


                // 处理标题
                if (mdString.StartsWith("#"))
                {
                    int level = 0;
                    foreach (char c in mdString)
                    {
                        if (c == '#')
                        {
                            level++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    string text = mdString.Substring(level).Trim();
                    htmlString += $"<h{level}>{text}</h{level}>";
                }

                //处理分割线
                else if ( mdString.Contains("---"))
                {
                    htmlString += "<hr/>";
                }
                //处理粗斜体
                else if (mdString.Contains("***"))
                {
                    htmlString += Regex.Replace(mdString, @"\*\*\*(.*?)\*\*\*", "<strong><em>$1</em></strong>");
                }
                else if (mdString.Contains("**"))
                {
                    // 处理粗体
                    htmlString += Regex.Replace(mdString, @"\*\*(.*?)\*\*", "<strong>$1</strong>");
                }
                // 处理斜体
                else if (mdString.Contains("*"))
                {
                    htmlString += Regex.Replace(mdString, @"\*(.*?)\*", "<em>$1</em>");
                }

                // 处理无序列表
                else if (mdString.StartsWith("- "))
                {
                    htmlString += "<ul>";
                    while (i < markdownStrings.Length && markdownStrings[i].StartsWith("- "))
                    {
                        htmlString += $"<li>{markdownStrings[i].Substring(2)}</li>";
                        i++;
                        if (i < markdownStrings.Length && Regex.IsMatch(markdownStrings[i], @"^\s{2}\d+\. "))
                        {
                            htmlString += "<ol>";
                            for (int j = i; j < markdownStrings.Length && Regex.IsMatch(markdownStrings[j], @"^\s{2}\d+\."); j++)
                            {
                                htmlString += $"<li>{markdownStrings[j].Substring(markdownStrings[j].IndexOf('.') + 2)}</li>";
                                i++;
                            }
                            htmlString += "</ol>";
                        }
                        else if (i < markdownStrings.Length && markdownStrings[i].StartsWith("  - "))
                        {
                            htmlString += "<ul>";
                            while (i < markdownStrings.Length && markdownStrings[i].StartsWith("  - "))
                            {
                                htmlString += $"<li>{markdownStrings[i].Substring(4)}</li>";
                                i++;
                            }
                            htmlString += "</ul>";
                        }
                    }

                    htmlString += "</ul>";
                    if (i < markdownStrings.Length)
                        i--;
                }
               
                //处理引用
                else if (mdString.StartsWith(">"))
                {                  
                    htmlString += "<blockquote>";
                    htmlString += "<p>";
                    while(i < markdownStrings.Length && markdownStrings[i].StartsWith(">"))
                    {
                        if (markdownStrings[i] == ">")
                            htmlString += "<p>";
                        htmlString += markdownStrings[i].Substring(1);
                        i++;
                        if (i < markdownStrings.Length && markdownStrings[i].StartsWith(">>"))
                            {
                            htmlString += "</p>";
                            htmlString += "<blockquote>";
                            htmlString += "<p>";
                            while(i < markdownStrings.Length && markdownStrings[i].StartsWith(">>"))
                            {
                                if (markdownStrings[i] == ">>")
                                    htmlString += "<p>";
                                htmlString += markdownStrings[i].Substring(2);
                                i++;
                                if (i < markdownStrings.Length && markdownStrings[i].StartsWith(">>>"))
                                {
                                    htmlString += "</p>";
                                    htmlString += "<blockquote>";
                                    htmlString += "<p>";
                                    while (i < markdownStrings.Length && markdownStrings[i].StartsWith(">>>"))
                                    {
                                        htmlString += markdownStrings[i].Substring(3);
                                        i++;
                                        if (markdownStrings[i - 1].Length >= 2)
                                        {
                                            if (markdownStrings[i - 1][markdownStrings[i - 1].Length - 1] == ' ' && markdownStrings[i - 1][markdownStrings[i - 1].Length - 2] == ' ')
                                            {
                                                htmlString += "<br>";
                                            }
                                        }
                                    }
                                    htmlString += "</p>";
                                }
                                if (markdownStrings[i - 1].Length >= 2)
                                {
                                    if (markdownStrings[i - 1][markdownStrings[i - 1].Length - 1] == ' ' && markdownStrings[i - 1][markdownStrings[i - 1].Length - 2] == ' ')
                                    {
                                        htmlString += "<br>";
                                    }
                                }
                                
                            }
                            htmlString += "</p>";
                        }
                        if (markdownStrings[i-1].Length >= 2)
                        {
                            if (markdownStrings[i - 1][markdownStrings[i - 1].Length - 1] == ' ' && markdownStrings[i - 1][markdownStrings[i - 1].Length - 2] == ' ')
                            {
                                htmlString += "<br>";
                            }
                        }
                    }
                    htmlString += "</p>";
                    htmlString += "</blockquote>";
                    i--;
                }
                //处理有序列表
                else if (Regex.IsMatch(mdString, @"^\d+\. "))
                {
                    htmlString += "<ol>";
                    for (int j = i; j < markdownStrings.Length && Regex.IsMatch(markdownStrings[j], @"^\d+\. "); j++)
                    {
                        htmlString += $"<li>{markdownStrings[j].Substring(markdownStrings[j].IndexOf('.') + 2)}</li>";
                        i++;
                        if (i < markdownStrings.Length && j < markdownStrings.Length && Regex.IsMatch(markdownStrings[i], @"^\s{2}\d+\. "))
                        {
                            htmlString += "<ol>";
                            for (int k = i; k < markdownStrings.Length && Regex.IsMatch(markdownStrings[k], @"^\s{2}\d+\."); k++)
                            {
                                htmlString += $"<li>{markdownStrings[k].Substring(markdownStrings[k].IndexOf('.') + 2)}</li>";
                                i++;
                                j++;
                            }
                            htmlString += "</ol>";
                        }
                        else if (i < markdownStrings.Length && j < markdownStrings.Length && markdownStrings[i].StartsWith("  - "))
                        {
                            htmlString += "<ul>";
                            while (i < markdownStrings.Length && j < markdownStrings.Length && markdownStrings[i].StartsWith("  - "))
                            {
                                htmlString += $"<li>{markdownStrings[i].Substring(4)}</li>";
                                i++;
                                j++;
                            }
                            htmlString += "</ul>";
                        }
                    }
                  
                    if (i < markdownStrings.Length)
                        i--;
                    htmlString += "</ol>";
                }
                // 处理图片
                else if (mdString.StartsWith("!"))
                {
                    Match match = Regex.Match(mdString, @"\!\[(.*?)\]\((.*?)\)");
                    string altText = match.Groups[1].Value;
                    string imageUrl = match.Groups[2].Value;
                    htmlString += $"<img src=\"{imageUrl}\" alt=\"{altText}\">";
                }
                // 处理链接
                else if (mdString.Contains("[") && mdString.Contains("]("))
                {
                    Match match = Regex.Match(mdString, @"\[(.*?)\]\((.*?)\)");
                    string text = match.Groups[1].Value;
                    string url = match.Groups[2].Value;
                    htmlString += $"<a href=\"{url}\">{text}</a>";
                }
                // 处理代码块
                else if (mdString.StartsWith("```"))
                {
                    string language = mdString.Substring(3).Trim();
                    htmlString += $"<pre><code class=\"language-{language}\">";
                    for (int j = i + 1; j < markdownStrings.Length && markdownStrings[j] != "```"; j++)
                    {
                        htmlString += EscapeCharacters(markdownStrings[j])+"\n";
                     
                        i++;
                    }

                    htmlString += "</code></pre>";
                    i++;
                }
                //处理代码行
                else if (mdString.Contains("`"))
                {
                    htmlString += Regex.Replace(mdString, @"\`(.*?)\`", "<code>$1</code>");
                }
                //处理表格
                else if (mdString.StartsWith("| "))
                {
                    htmlString += "<table border=\"1\">";
                    htmlString += "<tr>";
                    string[] hcells = mdString.Split('|');
                    foreach (string hcell in hcells)
                    {
                        if (!string.IsNullOrWhiteSpace(hcell))
                        {
                            htmlString += $"<th>{hcell.Trim()}</th>";
                        }
                    }

                    htmlString += "</tr>";
                    i++; // Increment i to move to the next line
                    for (; i < markdownStrings.Length && markdownStrings[i].StartsWith("| "); i++)
                    {
                        htmlString += "<tr>";
                        string[] cells = markdownStrings[i].Split('|');
                        foreach (string cell in cells)
                        {
                            string trimmedCell = cell.Trim();
                            bool allHyphens = true;
                            foreach (char c in trimmedCell)
                            {
                                if (c != '-')
                                {
                                    allHyphens = false;
                                    break;
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(trimmedCell) && !allHyphens)
                            {
                                htmlString += $"<td>{trimmedCell}</td>";
                            }
                        }

                        htmlString += "</tr>";
                    }

                    htmlString += "</table>";
                    i--;
                }



                //处理段落
                else if (mdString == "")
                {
                    htmlString += "<p>";
                }
                else
                {
                    htmlString += markdownStrings[i];
                }

                //处理换行
                if (mdString.Length >= 2)
                {
                    if (mdString[mdString.Length - 1] == ' ' && mdString[mdString.Length - 2] == ' ')
                    {
                        htmlString += "<br>";
                    }
                }
            }
            return htmlString;
        }
        
        static string EscapeCharacters(string input)
        {
            input = input.Replace("<", "&lt;");
            input = input.Replace(">", "&gt;");
            input = input.Replace("\"", "&quot;");
            input = input.Replace("'", "&#39;");
            return input;
        }
        static string[] GetLines(string input)
        {
            var result = new System.Collections.Generic.List<string>();
            string currentLine = "";

            foreach (char c in input)
            {
                if (c == '\n')
                {
                    // If current line is not empty, add it to result
                    if (!string.IsNullOrEmpty(currentLine))
                    {
                        result.Add(currentLine);
                        currentLine = "";
                    }
                    // If consecutive new lines, add an empty string to result
                    else if (result.Count == 0 || result[result.Count - 1] != "")
                    {
                        result.Add("");
                    }
                }
                else
                {
                    currentLine += c;
                }
            }

            // Add the last line if it's not empty
            if (!string.IsNullOrEmpty(currentLine))
            {
                result.Add(currentLine);
            }
            return result.ToArray();
        }
    }
}